import axios from "axios";
import { message } from "antd";
import { getToken } from "./auth";
const instance = axios.create({
  baseURL: "http://localhost:3009",
  timeout: 5000,
});
// 全局请求拦截
instance.interceptors.request.use(
  function (config) {
    config["headers"]["authorization"] = "Bearer " + getToken();
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 全局相应拦截
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response.data;
  },
  function (error) {
    message.error("出错了");
    if (error.response && error.response.status === 401) {
      window.location.href = "/#/login";
    }
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);
export const get = (url, params) => instance.get(url, { params });
export const post = (url, data) => instance.post(url, data);
export const put = (url, data) => instance.put(url, data);
export const del = (url) => instance.delete(url);
export default instance;
